using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using UnityEngine;

public class Levels : MonoBehaviour
{
    public GameObject[] containerObject;
    public GameObject containerPrefab;
    public int level;
    public JArray containArray;
    public List<Container> containers = new List<Container>();
    private int numberOfItemsToPick = 2;
    private int multiple = 1;

    public void InitLevels()
    {
        gameObject.name = "Levels";
        InitData();

        JArray levels = null;
        int _level = -1;
        if (Data.mode == 0)
        {
            levels = (JArray)Data.gameConfig["levels_normal"];
            _level = (int)UserManager.Instance.GetUserInfo()["CurrentLv"];

        }
        else if (Data.mode == 1)
        {
            levels = (JArray)Data.gameConfig["levels_limited"];
            _level = (int)UserManager.Instance.GetUserInfo()["LimitedLv"];
        }

        Debug.Log("当前关卡" + _level);

        level = Mathf.Min(_level, levels.Count);

        Data.countdownTime = (float)levels[level - 1]["time"];

        numberOfItemsToPick = (int)levels[level - 1]["type_count"];
        multiple = (int)levels[level - 1]["multiple"];

        containArray = (JArray)levels[level - 1]["cupboard"];
        //生成货架
        int count = 0;
        for (int i = 0; i < containerObject.Length; i++)
        {
            int index = (int)containArray[i];

            containerObject[i].SetActive(true);
            GameObject prefab = Instantiate(containerPrefab);
            prefab.name = "Container";
            prefab.transform.SetParent(containerObject[i].transform, false);
            Container container = prefab.GetComponent<Container>();
            var car = GetContainerColAndRow(i);

            if (index > 0)
            {
                container.InitContainer(car, count, index);
                containers.Add(container);
                count++;
            }
            else
            {
                container.InitRepair(car);
            }
        }

        //生成商品数据
        List<int> selectedItems = GetRandomItems(Constants.GOODS_COUNT, numberOfItemsToPick);
        Data.goodsData = GenerateContainerData(selectedItems);
        Debug.Log("注册物品goodsData" + Data.goodsData.Count);

        for (int i = 0; i < containers.Count; i++)  // 遍历容器
        {
            Container container = containers[i];
            container.InitFront();
            container.InitBack();
        }
    }

    public List<List<List<int>>> GenerateContainerData(List<int> goodsIndexArr)
    {
        // 结果集
        List<List<List<int>>> result = new List<List<List<int>>>();

        // 按照容器分组
        for (int i = 0; i < containers.Count; i++)
        {
            result.Add(new List<List<int>>());
        }

        Debug.Log("goodsIndexArr: " + string.Join(", ", goodsIndexArr));

        // 分组入柜，index=0代表留空
        for (int j = 0; j < goodsIndexArr.Count; j++)
        {
            int index = goodsIndexArr[j];
            List<List<int>> container = result[j % containers.Count]; // 第几个容器的数组

            if (container.Count > 0)
            {
                List<int> last = container[container.Count - 1]; // last为货架最上面一层的商品数组
                if (last.Count == 1)
                {
                    last.Add(index);
                }
                else if (last.Count == 2)
                {
                    if (index != 0 && last[0] == index && last[1] == index)
                    {
                        container.Add(new List<int> { index });
                    }
                    else
                    {
                        // 随机
                        if (Random.Range(0, 2) == 0) // 使用 Unity 的 Random.Range(0, 2) 代替 random(0, 1)
                        {
                            container.Add(new List<int> { index });
                        }
                        else
                        {
                            // 最后一组数据留空位
                            if (j == goodsIndexArr.Count - 1)
                            {
                                container.Add(new List<int> { index });
                            }
                            else
                            {
                                last.Add(index);
                            }
                        }
                    }
                }
                else
                {
                    container.Add(new List<int> { index });
                }
            }
            else
            {
                container.Add(new List<int> { index }); // 放了一个数组进去
            }
        }

        // Debug 输出，显示每个容器的内容
        for (int i = 0; i < containers.Count; i++)
        {
            List<List<int>> container = result[i];
            for (int j = 0; j < container.Count; j++)
            {
                List<int> element = container[j];
                // 输出每个容器中的每一层
                Debug.Log("Container " + i + ", Layer " + j + ": " + string.Join(", ", element));
            }
        }
        return result;
    }

    // 从0到goodsCount中随机选择numberOfItems个不重复的数字
    public List<int> GetRandomItems(int goodsCount, int numberOfItems)
    {
        List<int> allItems = new List<int>();
        for (int i = 0; i < goodsCount; i++)
        {
            allItems.Add(i);
        }

        // 使用 Fisher-Yates 洗牌算法随机打乱
        for (int i = 0; i < allItems.Count; i++)
        {
            int randomIndex = Random.Range(i, allItems.Count);
            int temp = allItems[i];
            allItems[i] = allItems[randomIndex];
            allItems[randomIndex] = temp;
        }

        // 获取随机选择的商品类型
        List<int> selectedItems = allItems.GetRange(0, numberOfItems);

        // 复制 selectedItems 三次
        List<int> tripledItems = new List<int>();
        foreach (var item in selectedItems)
        {
            for (int i = 0; i < multiple; i++)
            {
                tripledItems.Add(item);
            }
        }

        // 使用 Fisher-Yates 洗牌算法随机打乱 tripledItems
        for (int i = 0; i < tripledItems.Count; i++)
        {
            int randomIndex = Random.Range(i, tripledItems.Count);
            int temp = tripledItems[i];
            tripledItems[i] = tripledItems[randomIndex];
            tripledItems[randomIndex] = temp;
        }

        return tripledItems;
    }

    private void InitData()
    {
        for (int i = 0; i < containerObject.Length; i++)
        {
            containerObject[i].SetActive(false);
            foreach (Transform child in containerObject[i].transform)
            {
                Destroy(child.gameObject);
            }
        }
    }

    public (int col, int row) GetContainerColAndRow(int index)
    {
        int col = Mathf.FloorToInt(index % Constants.COLS);
        int row = Mathf.FloorToInt(index / Constants.COLS);

        return (col, row); // 返回元组
    }

    public void OnGenerateNewContainerData(List<int> shuffleList)
    {
        GoodsManager.Instance.ClearAllGoods();

        Data.goodsData = GenerateContainerData(shuffleList);
        Debug.Log("注册物品shuffleList" + Data.goodsData.Count);

        for (int i = 0; i < containers.Count; i++)  // 遍历容器
        {
            Container container = containers[i];
            container.RemoveGoodsCAllChild();

            container.InitFront();
            container.InitBack();
        }
    }

    public void OnChangeContainerStyle(int id)
    {

    }

}
